package com.caseProject.puremvc.mediator.gui
{
	import com.caseProject.puremvc.mediator.states.graphicStates.IdleState;
	import com.caseProject.puremvc.mediator.states.graphicStates.SelectState;
	import com.caseProject.puremvc.mediator.states.graphicStates.TransformState;
	
	import flash.display.DisplayObjectContainer;
	import flash.events.MouseEvent;
	
	public class AbstractGraphicBehavior extends Graphic
	{
		public function AbstractGraphicBehavior()
		{
			super();
			
			this.doubleClickEnabled = true;
			
			this.addEventListener (MouseEvent.MOUSE_DOWN, onDown);
			this.addEventListener (MouseEvent.DOUBLE_CLICK, onTransform);
			this.addEventListener(MouseEvent.CLICK, onSelect);
		}
		
		protected function onTransform(event:MouseEvent):void
		{
			this.setCurrentState(TransformState);			
		}
		
		protected function onSelect(event:MouseEvent):void
		{
			this.clearSelection ();
			this.setCurrentState(SelectState);			
		}
		
		private function clearSelection ():void {
			var container:DisplayObjectContainer = this.parent;
			var sg:Graphic;
			if (container != null) {
				for (var i:int = 0; i < container.numChildren; i++)  {
					var graphic:Graphic = container.getChildAt(i) as Graphic;
					if (graphic != null && graphic is Graphic) {
						graphic.setCurrentState(IdleState);
						graphic.enableDrag = false;
					}
				}
			}
		}
		
		private function onDown(event:MouseEvent):void {
			this.stage.addEventListener (MouseEvent.MOUSE_UP, onUp);
			this.stage.addEventListener (MouseEvent.MOUSE_MOVE, onMove);
			this.addEventListener (MouseEvent.MOUSE_UP, onUp);
			this.addEventListener (MouseEvent.MOUSE_MOVE, onMove);
			
			if (this.enableDrag){				
				this.startDrag ();
			}
		}
		
		protected function onMove(event:MouseEvent):void
		{
			
		}
		
		protected function onUp(event:MouseEvent):void
		{
			this.removeEventListener (MouseEvent.MOUSE_UP, onUp);
			this.removeEventListener (MouseEvent.MOUSE_MOVE, onMove);
			
			this.stage.removeEventListener (MouseEvent.MOUSE_UP, onUp);
			this.stage.removeEventListener (MouseEvent.MOUSE_MOVE, onMove);
			
			this.stopDrag ();
		}
	}
}